package com.shunwang.errors.client.spring;

import java.io.IOException;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;

import com.shunwang.errors.engine.builder.xml.LoggerXmlParser;
import com.shunwang.errors.engine.core.ErrorsHandler;

public class ErrorsHandlerXmlFactoryBean implements FactoryBean, InitializingBean{
	private Resource[] configLocations;
	private ErrorsHandler handler;
	
	public Object getObject() throws Exception {
		return handler;
	}

	public Class getObjectType() {
		return handler == null? ErrorsHandler.class:handler.getClass();
	}

	public boolean isSingleton() {
		return true;
	}

	public void afterPropertiesSet() throws Exception {
		handler = buildHandler();
	}

	private ErrorsHandler buildHandler() throws IOException {
		if(ObjectUtils.isEmpty(configLocations))
            throw new IllegalArgumentException("At least 1 'configLocation' entry is required");
		
		ErrorsHandler client = null;
		for(int i = 0; i < configLocations.length; i++)
        {
            java.io.InputStream is = configLocations[i].getInputStream();
            try
            {
                client = new LoggerXmlParser(is).parser();
            }
            catch(Exception ex)
            {
                throw new NestedIOException("Failed to parse config resource: " + configLocations[i], ex.getCause());
            }
        }
		return client;
	}

	public Resource[] getConfigLocations() {
		return configLocations;
	}

	public void setConfigLocations(Resource[] configLocations) {
		this.configLocations = configLocations;
	}
	
	public void setConfigLocation(Resource configLocation){
        configLocations = configLocation == null ? null : (new Resource[] {
            configLocation
        });
    }

}
